"""
AICOIN SAR策略实现
基于eth.md中的策略逻辑
"""
import pandas as pd
import numpy as np
import logging
from typing import Dict, Any, Tuple
import ta

from services.strategies.base import StrategyBase
from utils.indicators import Indicators

logger = logging.getLogger(__name__)

class SARStrategy(StrategyBase):
    """
    AICOIN SAR策略
    
    策略逻辑:
    1. 使用多个SAR参数来判断开仓和平仓信号
    2. 使用SAR227参数组合（2,2,7）作为平仓信号
    3. 使用SAR224和SAR225参数组合（2,2,4和2,2,5）作为开仓信号
    4. 结合趋势过滤条件
    5. 使用SuperTrend指标判断总体趋势方向
    
    参数:
    - take_profit: 止盈百分比，默认0.002 (0.2%)
    - step_trigger_percent: 阶梯触发百分比，默认0.003 (0.3%)
    - step_take_profit_increment: 每阶梯止盈增量，默认0.002 (0.2%)
    - risk_per_trade: 每笔交易风险，默认0.01 (1%)
    """
    
    def __init__(self, symbol: str, parameters: Dict[str, Any] = None):
        """
        初始化SAR策略
        
        策略参数说明：
        1. 止盈止损参数:
           - initial_take_profit: 初始止盈百分比，默认0.002 (0.2%)
           - step_trigger_percent: 阶梯触发百分比，默认0.003 (0.3%)
           - step_take_profit_increment: 每阶梯止盈增量，默认0.002 (0.2%)
           - exit_buffer_percent: 平仓缓冲区百分比，默认0.0005 (0.05%)
           - hard_take_profit_pct: 硬止盈百分比，默认0（不启用）。设置>0的值表示启用硬止盈，如0.05表示5%止盈
           - hard_stop_loss_pct: 硬止损百分比，默认>0表示启用

        2. 模式参数:
           - use_backtest_entry_mode: 是否使用回测模式的开仓信号判断，默认False
           - use_backtest_exit_mode: 是否使用回测模式的平仓价格计算，默认False

        3. SAR指标参数:
           - sar_exit_n2: SAR平仓-初始加速因子，默认2.0
           - sar_exit_n3: SAR平仓-加速因子步长，默认2.0
           - sar_exit_n4: SAR平仓-加速因子最大值，默认7.0
           
           - sar_entry1_n2: SAR开仓1-初始加速因子，默认2.0
           - sar_entry1_n3: SAR开仓1-加速因子步长，默认2.0
           - sar_entry1_n4: SAR开仓1-加速因子最大值，默认4.0
           
           - sar_entry2_n2: SAR开仓2-初始加速因子，默认2.0
           - sar_entry2_n3: SAR开仓2-加速因子步长，默认2.0
           - sar_entry2_n4: SAR开仓2-加速因子最大值，默认5.0
           
           - sar_filter_n2: SAR过滤-初始加速因子，默认2.0
           - sar_filter_n3: SAR过滤-加速因子步长，默认2.0
           - sar_filter_n4: SAR过滤-加速因子最大值，默认3.0
           
           - sar_entry_offset_pct: SAR开仓偏移百分比，默认1.2%

        4. SuperTrend参数:
           - supertrend_periods: 周期，默认10
           - supertrend_multiplier: 乘数，默认3.9
           - supertrend_source: 价格源，默认'hl2'（最高价和最低价的平均）
           
        5. 交易参数:
           - margin_size: 保证金大小，用于计算仓位（单位USDT）
           - leverage: 杠杆倍数，默认25
        """
        super().__init__(symbol, parameters)
        
        params = parameters or {}
        # 止盈参数
        self.initial_take_profit = params.get('initial_take_profit', 0.002)  # 初始止盈0.2%
        self.step_trigger_percent = params.get('step_trigger_percent', 0.003)  # 阶梯步长0.3%
        self.step_take_profit_increment = params.get('step_take_profit_increment', 0.002)  # 每阶梯上调0.2%
        self.exit_buffer_percent = params.get('exit_buffer_percent', 0.0005)  # 平仓缓冲区0.05%
        self.use_backtest_exit_mode = params.get('use_backtest_exit_mode', False)  # 是否使用回测模式的平仓价格计算
        self.use_backtest_entry_mode = params.get('use_backtest_entry_mode', False)  # 是否使用回测模式的开仓信号判断
        
        # 硬止损和硬止盈参数
        self.hard_stop_loss_pct = params.get('hard_stop_loss_pct', 0.01)  # 硬止损百分比，默认为0.01（1%）
        self.hard_take_profit_pct = params.get('hard_take_profit_pct', 0.0)  # 硬止盈百分比，默认为0（不启用）
        
        # SAR参数
        self.sar_exit_params = {
            'n2': params.get('sar_exit_n2', 2.0),  # 初始加速因子
            'n3': params.get('sar_exit_n3', 2.0),  # 加速因子步长
            'n4': params.get('sar_exit_n4', 7.0)   # 加速因子最大值
        }
        
        self.sar_entry_params1 = {
            'n2': params.get('sar_entry1_n2', 2.0),
            'n3': params.get('sar_entry1_n3', 2.0),
            'n4': params.get('sar_entry1_n4', 4.0)
        }
        
        self.sar_entry_params2 = {
            'n2': params.get('sar_entry2_n2', 2.0),
            'n3': params.get('sar_entry2_n3', 2.0),
            'n4': params.get('sar_entry2_n4', 5.0)
        }
        
        self.sar_filter_params = {
            'n2': params.get('sar_filter_n2', 2.0),
            'n3': params.get('sar_filter_n3', 2.0),
            'n4': params.get('sar_filter_n4', 3.0)
        }
        
        # SAR开仓偏移百分比
        self.sar_entry_offset_pct = params.get('sar_entry_offset_pct', 1.2)
        
        # SuperTrend参数
        self.supertrend_periods = params.get('supertrend_periods', 10)
        self.supertrend_multiplier = params.get('supertrend_multiplier', 3.9)
        self.supertrend_source = params.get('supertrend_source', 'hl2')

        # 最新成交价，用于外部修改
        self.last_price = None
        
        # 状态变量
        self.long_price = None
        self.short_price = None
        self.long_max_profit_price = None
        self.short_max_profit_price = None
        self.long_stop_price = None
        self.short_stop_price = None
        self.is_long_take_profit = False
        self.is_short_take_profit = False
        self.long_step_level = 0
        self.short_step_level = 0
        
        # 新增：记录最近一次交易的K线时间和状态
        self.last_trade_candle_time = None
        self.last_candle_had_exit = False  # 标记同一根K线是否有平仓操作
        
        # 记录硬止盈和硬止损状态
        hard_tp_status = f"{self.hard_take_profit_pct*100:.2f}%" if self.hard_take_profit_pct > 0 else "关闭"
        hard_sl_status = f"{self.hard_stop_loss_pct*100:.2f}%"
        
        self.logger.info(f"AICOIN SAR策略初始化: 初始止盈={self.initial_take_profit*100:.2f}%, "
                        f"阶梯触发={self.step_trigger_percent*100:.2f}%, "
                        f"波动率={self.sar_entry_offset_pct}, "
                        f"阶梯增量={self.step_take_profit_increment*100:.2f}%, "
                        f"硬止盈={hard_tp_status}, "
                        f"硬止损={hard_sl_status}, "
                        f"开仓模式={'回测' if self.use_backtest_entry_mode else '实盘'}, "
                        f"平仓模式={'回测' if self.use_backtest_exit_mode else '实盘'}")
    
    def prepare_data(self, raw_data: pd.DataFrame) -> pd.DataFrame:
        """
        准备数据，计算技术指标
        """
        df = raw_data.copy()
        
        # 确保数据按时间排序
        df = df.sort_values('datetime')
        
        # 计算SuperTrend指标
        supertrend_result = Indicators.supertrend(
            df['high'], 
            df['low'], 
            df['close'],
            periods=self.supertrend_periods,
            multiplier=self.supertrend_multiplier,
            source=self.supertrend_source
        )
        
        df['supertrend_trend'] = supertrend_result['trend']
        df['supertrend_up'] = supertrend_result['up']
        df['supertrend_down'] = supertrend_result['down']
        df['supertrend_buy_signal'] = supertrend_result['buy_signal']
        df['supertrend_sell_signal'] = supertrend_result['sell_signal']
        
        # 计算SAR227 - 用于平仓信号
        df['sar_exit'] = Indicators.aicoin_sar(df, 
                                              self.sar_exit_params['n2'],
                                              self.sar_exit_params['n3'], 
                                              self.sar_exit_params['n4'])
        
        # 计算SAR224 - 用于开仓信号1
        df['sar_entry1'] = Indicators.aicoin_sar(df, 
                                                self.sar_entry_params1['n2'],
                                                self.sar_entry_params1['n3'], 
                                                self.sar_entry_params1['n4'])
        
        # 计算SAR225 - 用于开仓信号2
        df['sar_entry2'] = Indicators.aicoin_sar(df, 
                                               self.sar_entry_params2['n2'],
                                               self.sar_entry_params2['n3'], 
                                               self.sar_entry_params2['n4'])
        
        # 计算SAR223 - 用于过滤
        df['sar_filter'] = Indicators.aicoin_sar(df, 
                                                self.sar_filter_params['n2'],
                                                self.sar_filter_params['n3'], 
                                                self.sar_filter_params['n4'])
        
        # 计算ADX趋势强度指标
        adx_period = 14
        df['tr'] = ta.volatility.average_true_range(high=df['high'], low=df['low'], close=df['close'], window=1)
        df['adx'] = ta.trend.adx(high=df['high'], low=df['low'], close=df['close'], window=adx_period)
        
        # 计算RVI动能指标 (使用自定义实现)
        df['rvi_up'] = np.maximum(df['close'] - df['close'].shift(1), 0)
        df['rvi_down'] = np.maximum(df['close'].shift(1) - df['close'], 0)
        
        # 加权动能（近4根K线，包括当前）
        weights = np.array([1, 2, 2, 1])
        df['rvi_up_avg'] = df['rvi_up'].rolling(window=4).apply(lambda x: np.sum(x * weights[:len(x)]) / np.sum(weights[:len(x)]), raw=False)
        df['rvi_down_avg'] = df['rvi_down'].rolling(window=4).apply(lambda x: np.sum(x * weights[:len(x)]) / np.sum(weights[:len(x)]), raw=False)
        
        # 计算RVI
        df['rvi'] = 100 * df['rvi_up_avg'] / (df['rvi_up_avg'] + df['rvi_down_avg'])
        
        # 计算ATR
        df['atr'] = ta.volatility.average_true_range(high=df['high'], low=df['low'], close=df['close'], window=14)
        
        # 计算过滤器条件
        df['adx_pass'] = df['adx'] > 20
        df['rvi_pass'] = (df['rvi'] - 50).abs() > 5
        df['atr_pass'] = df['atr'] < df['atr'].shift(1) * 1.4
        df['trend_filter'] = df['adx_pass'] & df['rvi_pass'] & df['atr_pass']
        
        # 计算开仓和平仓信号
        # SAR平仓信号
        df['exit_long_signal'] = (df['close'] < df['sar_exit']) & (df['close'].shift(1) >= df['sar_exit'].shift(1))
        df['exit_short_signal'] = (df['close'] > df['sar_exit']) & (df['close'].shift(1) <= df['sar_exit'].shift(1))
        
        # SAR开仓信号条件
        df['sar_buy'] = ((df['open'] - df['sar_entry2']) / df['sar_entry2'] * 100 > 0) & \
                        ((df['open'] - df['sar_entry2']) / df['sar_entry2'] * 100 < self.sar_entry_offset_pct)
        df['sar_sell'] = ((df['sar_entry2'] - df['open']) / df['sar_entry2'] * 100 > 0) & \
                         ((df['sar_entry2'] - df['open']) / df['sar_entry2'] * 100 < self.sar_entry_offset_pct)
        df['sar_B'] = df['open'] > df['sar_filter']
        df['sar_S'] = df['open'] < df['sar_filter']
        
        # 价格区间过滤器 - 用于所有模式
        price_range_filter = (df['high'] - df['low']) / df['open'] < 0.025  # 价格区间过滤器

        # 多头：前一根K线的SAR线低于当前K线的最高价且高于当前K线的最低价
        df['entry1_buy_signal'] = (df['high'] > df['sar_entry1'].shift(1)) & \
                                  (df['low'] < df['sar_entry1'].shift(1)) & \
                                  price_range_filter

        df['entry2_buy_signal'] = (df['high'] > df['sar_entry2'].shift(1)) & \
                                  (df['low'] < df['sar_entry2'].shift(1)) & \
                                  price_range_filter

        # 空头：前一根K线的SAR线高于当前K线的最低价且低于当前K线的最高价
        df['entry1_sell_signal'] = (df['low'] < df['sar_entry1'].shift(1)) & \
                                   (df['high'] > df['sar_entry1'].shift(1)) & \
                                   price_range_filter

        df['entry2_sell_signal'] = (df['low'] < df['sar_entry2'].shift(1)) & \
                                   (df['high'] > df['sar_entry2'].shift(1)) & \
                                   price_range_filter
        
        # 综合信号 - 增加SuperTrend趋势方向判断
        df['long_signal'] = df['entry1_buy_signal'] & df['entry2_buy_signal'] & df['sar_buy'] & df['trend_filter'] & df['sar_B'] & (df['supertrend_trend'] == 1)
        df['short_signal'] = df['entry1_sell_signal'] & df['entry2_sell_signal'] & df['sar_sell'] & df['trend_filter'] & df['sar_S'] & (df['supertrend_trend'] == -1)
        
        return df
    
    async def check_entry_signal(self, data: pd.DataFrame) -> Tuple[bool, Dict[str, Any]]:
        """
        检查开仓信号
        
        Returns:
            (是否有信号，信号详情)
        """
        # 获取最新数据
        latest = data.iloc[-1]
        
        # 获取前一根K线的数据
        if len(data) > 1:
            prev = data.iloc[-2]
            prev_sar_entry1 = prev['sar_entry1']
            prev_sar_entry2 = prev['sar_entry2']
        else:
            prev = None
            prev_sar_entry1 = None
            prev_sar_entry2 = None

        long_signal = latest['long_signal']
        short_signal = latest['short_signal']
        
        # 无论回测还是实盘，都使用SAR平均值作为开仓价格
        entry_price = latest['close']  # 默认使用收盘价作为开仓价格
        if (long_signal or short_signal) and prev_sar_entry1 is not None and prev_sar_entry2 is not None:
            entry_price = (prev_sar_entry1 + prev_sar_entry2) / 2
        
        # 信号数据
        signal_data = {
            'datetime': latest['datetime'].isoformat(),
            'price': latest['close'],
            'sar_entry1': latest['sar_entry1'],
            'sar_entry2': latest['sar_entry2'],
            'prev_sar_entry1': prev_sar_entry1,
            'prev_sar_entry2': prev_sar_entry2,
            'sar_filter': latest['sar_filter'],
            'adx': latest['adx'],
            'rvi': latest['rvi'],
            'supertrend_trend': latest['supertrend_trend']
        }
        
        # 检查是否是同一根K线
        current_candle_time = latest['datetime'].strftime('%Y-%m-%d %H:%M:%S')
        
        # 如果是同一根K线并且已经有平仓操作，则不再开仓
        if self.last_trade_candle_time == current_candle_time and self.last_candle_had_exit:
            self.logger.debug(f"跳过开仓信号检查：当前K线 {current_candle_time} 已有平仓操作")
            return False, signal_data
        
        # 多头信号
        if long_signal and self.long_price is None and prev_sar_entry1 is not None and prev_sar_entry2 is not None:
            signal_data['direction'] = '多'
            
            self.long_price = entry_price
            signal_data['price'] = entry_price
            
            self.long_max_profit_price = latest['high']
            self.is_long_take_profit = False
            self.long_step_level = 0
            self.long_stop_price = None
            
            # 更新最近交易K线时间
            self.last_trade_candle_time = current_candle_time
            self.last_candle_had_exit = False
            
            # 计算硬止损价格
            if self.hard_stop_loss_pct > 0:
                hard_stop_loss_price = self.long_price * (1 - self.hard_stop_loss_pct)
                signal_data['hard_stop_loss_price'] = hard_stop_loss_price
                signal_data['hard_stop_loss_pct'] = self.hard_stop_loss_pct * 100
                self.logger.info(f"多头开仓: 价格={self.base_format_price(self.long_price)}, 前SAR224={self.base_format_price(prev_sar_entry1)}, 前SAR225={self.base_format_price(prev_sar_entry2)}, 硬止损价={self.base_format_price(hard_stop_loss_price)} (跌幅 {self.hard_stop_loss_pct*100:.2f}%)")
            
            signal_data['reason'] = (
                f"SAR多头信号: 前SAR224={self.base_format_price(prev_sar_entry1)}, 前SAR225={self.base_format_price(prev_sar_entry2)}, "
                f"价格={self.base_format_price(entry_price)}, SuperTrend={latest['supertrend_trend']}, "
                f"ADX={latest['adx']:.2f}, RVI={latest['rvi']:.2f}"
            )
            
            return True, signal_data
            
        # 空头信号
        elif short_signal and self.short_price is None and prev_sar_entry1 is not None and prev_sar_entry2 is not None:
            signal_data['direction'] = '空'
            
            self.short_price = entry_price
            signal_data['price'] = entry_price
            
            self.short_max_profit_price = latest['low']
            self.is_short_take_profit = False
            self.short_step_level = 0
            self.short_stop_price = None
            
            # 更新最近交易K线时间
            self.last_trade_candle_time = current_candle_time
            self.last_candle_had_exit = False
            
            # 计算硬止损价格
            if self.hard_stop_loss_pct > 0:
                hard_stop_loss_price = self.short_price * (1 + self.hard_stop_loss_pct)
                signal_data['hard_stop_loss_price'] = hard_stop_loss_price
                signal_data['hard_stop_loss_pct'] = self.hard_stop_loss_pct * 100
                self.logger.info(f"空头开仓: 价格={self.base_format_price(self.short_price)}, 前SAR224={self.base_format_price(prev_sar_entry1)}, 前SAR225={self.base_format_price(prev_sar_entry2)}, 硬止损价={self.base_format_price(hard_stop_loss_price)} (涨幅 {self.hard_stop_loss_pct*100:.2f}%)")
            
            signal_data['reason'] = (
                f"SAR空头信号: 前SAR224={self.base_format_price(prev_sar_entry1)}, 前SAR225={self.base_format_price(prev_sar_entry2)}, "
                f"价格={self.base_format_price(entry_price)}, SuperTrend={latest['supertrend_trend']}, "
                f"ADX={latest['adx']:.2f}, RVI={latest['rvi']:.2f}"
            )
            
            return True, signal_data
        
        return False, signal_data
    
    async def check_exit_signal(self, data: pd.DataFrame, entry_data: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]:
        """
        检查平仓信号
        
        Args:
            data: K线数据
            entry_data: 开仓时的信号数据
            
        Returns:
            (是否有信号，信号详情)
        """
        # 获取最新数据
        latest = data.iloc[-1]
        
        # 获取开仓方向和价格
        direction = entry_data.get('direction')
        
        # 信号数据
        signal_data = {
            'datetime': latest['datetime'].isoformat(),
            'price': latest['close'],
            'sar_exit': latest['sar_exit']
        }

        # 获取当前K线时间
        current_candle_time = latest['datetime'].strftime('%Y-%m-%d %H:%M:%S')

        # --- 硬止损和硬止盈检查 (最高优先级) ---
        # 硬止损逻辑
        if self.hard_stop_loss_pct > 0:
            if direction == '多' and self.long_price is not None:
                stop_loss_price = self.long_price * (1 - self.hard_stop_loss_pct)
                if latest['low'] <= stop_loss_price:
                    # 使用精确的止损价格而不是最低价
                    signal_data['price'] = stop_loss_price
                    signal_data['reason'] = f"硬止损触发: 价格触及 {self.base_format_price(stop_loss_price)} (跌幅 {self.hard_stop_loss_pct*100:.2f}%)"
                    self.logger.warning(f"硬止损触发: 多头仓位在 {self.base_format_price(stop_loss_price)} 平仓 (开仓价: {self.base_format_price(self.long_price)}, 止损比例: {self.hard_stop_loss_pct*100:.2f}%)")
                    
                    # 更新最近交易K线时间和状态
                    self.last_trade_candle_time = current_candle_time
                    self.last_candle_had_exit = True
                    
                    # 重置状态
                    self.long_price = None
                    return True, signal_data
            
            elif direction == '空' and self.short_price is not None:
                stop_loss_price = self.short_price * (1 + self.hard_stop_loss_pct)
                if latest['high'] >= stop_loss_price:
                    # 使用精确的止损价格而不是最高价
                    signal_data['price'] = stop_loss_price
                    signal_data['reason'] = f"硬止损触发: 价格触及 {self.base_format_price(stop_loss_price)} (涨幅 {self.hard_stop_loss_pct*100:.2f}%)"
                    self.logger.warning(f"硬止损触发: 空头仓位在 {self.base_format_price(stop_loss_price)} 平仓 (开仓价: {self.base_format_price(self.short_price)}, 止损比例: {self.hard_stop_loss_pct*100:.2f}%)")
                    
                    # 更新最近交易K线时间和状态
                    self.last_trade_candle_time = current_candle_time
                    self.last_candle_had_exit = True
                    
                    # 重置状态
                    self.short_price = None
                    return True, signal_data
        
        # 硬止盈逻辑 (新增)
        if self.hard_take_profit_pct > 0:
            if direction == '多' and self.long_price is not None:
                take_profit_price = self.long_price * (1 + self.hard_take_profit_pct)
                if latest['high'] >= take_profit_price:
                    # 使用精确的止盈价格而不是最高价
                    signal_data['price'] = take_profit_price
                    signal_data['reason'] = f"硬止盈触发: 价格触及 {self.base_format_price(take_profit_price)} (涨幅 {self.hard_take_profit_pct*100:.2f}%)"
                    self.logger.warning(f"硬止盈触发: 多头仓位在 {self.base_format_price(take_profit_price)} 平仓 (开仓价: {self.base_format_price(self.long_price)}, 止盈比例: {self.hard_take_profit_pct*100:.2f}%)")
                    
                    # 更新最近交易K线时间和状态
                    self.last_trade_candle_time = current_candle_time
                    self.last_candle_had_exit = True
                    
                    # 重置状态
                    self.long_price = None
                    return True, signal_data
            
            elif direction == '空' and self.short_price is not None:
                take_profit_price = self.short_price * (1 - self.hard_take_profit_pct)
                if latest['low'] <= take_profit_price:
                    # 使用精确的止盈价格而不是最低价
                    signal_data['price'] = take_profit_price
                    signal_data['reason'] = f"硬止盈触发: 价格触及 {self.base_format_price(take_profit_price)} (跌幅 {self.hard_take_profit_pct*100:.2f}%)"
                    self.logger.warning(f"硬止盈触发: 空头仓位在 {self.base_format_price(take_profit_price)} 平仓 (开仓价: {self.base_format_price(self.short_price)}, 止盈比例: {self.hard_take_profit_pct*100:.2f}%)")
                    
                    # 更新最近交易K线时间和状态
                    self.last_trade_candle_time = current_candle_time
                    self.last_candle_had_exit = True
                    
                    # 重置状态
                    self.short_price = None
                    return True, signal_data
        
        # 多头平仓逻辑
        if direction == '多' and self.long_price is not None:
            # 更新最大利润价格
            self.long_max_profit_price = max(self.long_max_profit_price, latest['high'])
            
            # 计算利润率
            long_profit_ratio = (self.long_max_profit_price - self.long_price) / self.long_price
            long_step = int(long_profit_ratio / self.step_trigger_percent)
            
            # 触发初始止盈，锁定底线
            if not self.is_long_take_profit:
                long_initial_tp_price = self.long_price * (1 + self.initial_take_profit)
                if self.long_max_profit_price >= long_initial_tp_price * 1.0001:
                    self.long_stop_price = long_initial_tp_price  # 锁定初始止盈底线
                    self.is_long_take_profit = True
            
            # 阶梯上调止盈线
            if self.is_long_take_profit and long_step > self.long_step_level:
                self.long_step_level = long_step
                new_stop = self.long_price * (1 + self.initial_take_profit + 
                                             self.long_step_level * self.step_take_profit_increment)
                if self.long_stop_price is not None:
                    self.long_stop_price = max(self.long_stop_price, new_stop)
                else:
                    self.long_stop_price = new_stop
            
            # 阶梯止盈平仓 - 兼容两种模式
            if self.is_long_take_profit and self.long_stop_price is not None and latest['close'] <= self.long_stop_price:
                if self.use_backtest_exit_mode:
                    # 回测模式：使用阶梯价格减去缓冲区
                    exit_price = self.long_stop_price * (1 - self.exit_buffer_percent)
                    # 确保平仓价格不低于收盘价（防止滑点过大）
                    exit_price = max(exit_price, latest['close'])
                    signal_data['reason'] = f"多头阶梯止盈(回测): 当前价格={self.base_format_price(latest['close'])} <= 止盈价={self.base_format_price(self.long_stop_price)}, 平仓价={self.base_format_price(exit_price)}"
                else:
                    # 实盘模式：直接使用收盘价
                    exit_price = latest['close']
                    signal_data['reason'] = f"多头阶梯止盈(实盘): 当前价格={self.base_format_price(latest['close'])} <= 止盈价={self.base_format_price(self.long_stop_price)}"
                
                signal_data['price'] = exit_price
                
                # 更新最近交易K线时间和状态
                self.last_trade_candle_time = current_candle_time
                self.last_candle_had_exit = True
                
                # 重置状态
                self.long_price = None
                self.long_max_profit_price = None
                self.long_stop_price = None
                self.is_long_take_profit = False
                self.long_step_level = 0
                return True, signal_data
            
            # SAR信号平仓
            if latest['exit_long_signal']:
                signal_data['reason'] = f"SAR平仓信号: 价格={self.base_format_price(latest['close'])} < SAR227={self.base_format_price(latest['sar_exit'])}"
                
                # 更新最近交易K线时间和状态
                self.last_trade_candle_time = current_candle_time
                self.last_candle_had_exit = True
                
                # 重置状态
                self.long_price = None
                self.long_max_profit_price = None
                self.long_stop_price = None
                self.is_long_take_profit = False
                self.long_step_level = 0
                return True, signal_data
        
        # 空头平仓逻辑
        elif direction == '空' and self.short_price is not None:
            # 更新最小利润价格
            self.short_max_profit_price = min(self.short_max_profit_price, latest['low'])
            
            # 计算利润率
            short_profit_ratio = (self.short_price - self.short_max_profit_price) / self.short_price
            short_step = int(short_profit_ratio / self.step_trigger_percent)
            
            # 触发初始止盈，锁定底线
            if not self.is_short_take_profit:
                short_initial_tp_price = self.short_price * (1 - self.initial_take_profit)
                if self.short_max_profit_price <= short_initial_tp_price * 0.9999:
                    self.short_stop_price = short_initial_tp_price  # 锁定初始止盈底线
                    self.is_short_take_profit = True
            
            # 阶梯上调止盈线
            if self.is_short_take_profit and short_step > self.short_step_level:
                self.short_step_level = short_step
                new_stop = self.short_price * (1 - self.initial_take_profit - 
                                              self.short_step_level * self.step_take_profit_increment)
                if self.short_stop_price is not None:
                    self.short_stop_price = min(self.short_stop_price, new_stop)
                else:
                    self.short_stop_price = new_stop
            
            # 阶梯止盈平仓 - 兼容两种模式
            if self.is_short_take_profit and self.short_stop_price is not None and latest['close'] >= self.short_stop_price:
                if self.use_backtest_exit_mode:
                    # 回测模式：使用阶梯价格加上缓冲区
                    exit_price = self.short_stop_price * (1 + self.exit_buffer_percent)
                    # 确保平仓价格不高于收盘价（防止滑点过大）
                    exit_price = min(exit_price, latest['close'])
                    signal_data['reason'] = f"空头阶梯止盈(回测): 当前价格={self.base_format_price(latest['close'])} >= 止盈价={self.base_format_price(self.short_stop_price)}, 平仓价={self.base_format_price(exit_price)}"
                else:
                    # 实盘模式：直接使用收盘价
                    exit_price = latest['close']
                    signal_data['reason'] = f"空头阶梯止盈(实盘): 当前价格={self.base_format_price(latest['close'])} >= 止盈价={self.base_format_price(self.short_stop_price)}"
                
                signal_data['price'] = exit_price
                
                # 更新最近交易K线时间和状态
                self.last_trade_candle_time = current_candle_time
                self.last_candle_had_exit = True
                
                # 重置状态
                self.short_price = None
                self.short_max_profit_price = None
                self.short_stop_price = None
                self.is_short_take_profit = False
                self.short_step_level = 0
                return True, signal_data
            
            # SAR信号平仓
            if latest['exit_short_signal']:
                signal_data['reason'] = f"SAR平仓信号: 价格={self.base_format_price(latest['close'])} > SAR227={self.base_format_price(latest['sar_exit'])}"
                
                # 更新最近交易K线时间和状态
                self.last_trade_candle_time = current_candle_time
                self.last_candle_had_exit = True
                
                # 重置状态
                self.short_price = None
                self.short_max_profit_price = None
                self.short_stop_price = None
                self.is_short_take_profit = False
                self.short_step_level = 0
                return True, signal_data
        
        return False, signal_data
